package acwing;

import java.io.IOException;
import java.util.Scanner;

public class DeepFirst {

    static int[] num = new int[10];
    static int idxOfZero;
    static int[] xx = new int[]{0, -1, 0, 1};
    static int[] yy = new int[]{-1, 0, 1, 0};
    static int maxDeep = 0;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        String[] tem = in.nextLine().trim().split("\\s+");
        for(int i = 0; i < tem.length; i ++ ){
            if(tem[i].charAt(0) >= '0' && tem[i].charAt(0) <= '9')
                num[i] = tem[i].charAt(0) - '0';
            else {
                num[i] = 0;
                idxOfZero = i;
            }
        }
        int k = 0;
        for(int i = 0; i < 9; i ++){
            for(int j = i + 1; j < 9; j ++){
                if(num[j] == 0)
                    continue;
                if(num[i] > num[j])
                    k ++;
            }
        }
        if((k&1) == 1){
            System.out.println(-1);
            return;
        }
        while(!dfs(0, idxOfZero)){
            maxDeep += 1;
        }
        System.out.println(maxDeep);
    }
    static boolean dfs(int deep,int idx){
        int v = value();
        if(v == 0)
            return true;
        if(v + deep > maxDeep)
            return false;
        int x = idx / 3;
        int y = idx % 3;
        for(int i = 0; i < 4; i ++){
            int x1 = x + xx[i];
            int y1 = y + yy[i];
            if(x1 < 0 || y1 < 0 || x1 >= 3 || y1 >= 3)
                continue;
            num[x * 3 + y] = num[x1 * 3 + y1];
            num[x1 * 3+ y1] = 0;
            if (dfs(deep + 1,x1 * 3 + y1))
                return true;
            num[x1 * 3 + y1] = num[x * 3 + y];
            num[x * 3 + y] = 0;
        }
        return false;
    }

    static int value(){
        int cnt = 0;
        for(int i = 0; i < 9; i ++){
            if(num[i] == 0){
                continue;
            }
            int x1 = i / 3;
            int y1 = i % 3;
            int x2 = (num[i] - 1) / 3;
            int y2 = (num[i] - 1) % 3;
            int v = Math.abs(x1 - x2) + Math.abs(y1 - y2);
            cnt += v;
        }
        return cnt;
    }
}
